"""
DESCRIPTION
Computes a sum of values per each unique entry appearing across multiple files, specified as inputs

ARGUMENTS
1. input1
2. input2
...
N. inputN
N+1. output

CONTACT
timo.p.erkkila@tut.fi
http://www.cs.tut.fi/~erkkila2/
"""

import sys,csv

sums = {}

input_files = sys.argv[1:-1]

for input_file in input_files:
    listreader = csv.reader(open(input_file,'r'),delimiter='\t')
    for line in listreader:
        entry,value = line
        if sums.get(entry,'NA') == 'NA':
            sums[entry] = float(value)
        else:
            sums[entry] += float(value)

sums = sums.items()
sums.sort(key = lambda tup: tup[1])
sums.reverse()

listwriter = csv.writer(open(sys.argv[-1],'w'),delimiter='\t')

for k,v in sums:
    listwriter.writerow([k,v])

